package main

import (
	"fmt"
	"oa-rest/common"
	"oa-rest/config"
	"oa-rest/middleware"
	"oa-rest/models/dashboard"
	"oa-rest/models/docindex"
	"oa-rest/models/docqa"
	"oa-rest/models/document"
	"oa-rest/models/gendoc"
	"oa-rest/models/incoming"
	"oa-rest/models/lnk"
	"oa-rest/models/local"
	"oa-rest/models/meeting"
	"oa-rest/models/message"
	"oa-rest/models/minio"
	"oa-rest/models/sharefile"
	"oa-rest/models/summary"
	"oa-rest/models/task"
	"oa-rest/models/user"
	"oa-rest/ws"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

func main() {
	// 现在所有时间操作都使用设置的时区
	initTimeZone()
	config.InitEnv()
	db, err := common.ConnectDb()
	if err != nil {
		panic("初始化iot数据库失败：" + err.Error())
	}
	common.InitAIClient()
	common.InitMinioClient()

	// 启动websocket服务
	go ws.Start()

	r := gin.New()
	r.Use(middleware.RequestId())
	r.Use(middleware.OpLog())
	r.Use(middleware.Cors()) // 跨域请求
	r.Use(gin.Recovery())

	apiV1 := r.Group("/api")
	// 不需要鉴权的写在这里

	// MinIO文件管理服务（公开接口，不需要JWT）
	minioService := minio.NewMinioService()
	minioService.RegisterRoutes(apiV1)

	if config.JwtEnabled {
		apiV1.Use(middleware.JWT()) // token 验证
	}
	// 需要鉴权的写在这里
	//ccImp := cc.NewCc(db)
	//ccImp.InitApi(apiV1)

	userImp := user.NewUser(db)
	userImp.InitApi(apiV1)

	// 注册 admin 专属用户列表接口
	adminUserService := user.NewAdminUserService(db)
	apiV1.GET("/admin/users", adminUserService.GetAllUsersHandler)
	apiV1.PUT("/admin/users/status", adminUserService.UpdateUserStatusHandler)
	apiV1.PUT("/admin/users/password", adminUserService.ForceResetPasswordHandler)
	apiV1.POST("/admin/users", adminUserService.AddUserHandler)
	apiV1.DELETE("/admin/users", adminUserService.DeleteUserHandler)

	// task
	taskTemplateDao := task.NewTaskTemplateDAO(db)
	taskTemplateService := task.NewTaskTemplateService(taskTemplateDao)
	taskTemplateService.RegisterRoutes(apiV1)

	// fileinfo
	fileInfoDao := document.NewFileInfoDAO(db)
	fileInfoService := document.NewFileInfoService(fileInfoDao)
	fileInfoHandler := document.NewFileInfoHandler(fileInfoService)
	fileInfoHandler.RegisterRoutes(apiV1)

	// message
	messageDao := message.NewMessageDAO(db)
	messageService := message.NewMessageService(messageDao)
	messageService.RegisterRoutes(apiV1)
	// 注册机器人文档相关路由
	messageService.RegisterRobotDocsRoutes(apiV1)

	log.Println("============1================")
	//cti.QuerySearch()
	//cti.Audio2textByUrl()
	//testMinio()

	log.Println("============2================")

	// 本地查询服务
	apiV1.POST("/local/query", local.LocalQueryHandler)
	apiV1.POST("/local/queryForm", local.LocalQueryFormHandler)

	// 文档问答服务
	apiV1.POST("/docqa/selectAndAsk", docqa.SelectAndAskHandler)
	apiV1.POST("/docqa/ask", docqa.AskHandler)
	apiV1.POST("/docqa/selectAndAskForm", docqa.SelectAndAskFormHandler)
	apiV1.POST("/docqa/askForm", docqa.AskFormHandler)

	// 文档索引服务
	docindex.RegisterRoutes(apiV1)

	// 公文生成服务（公开接口，不需要JWT）
	apiV1.GET("/templates", document.GetTemplatesHandler)
	apiV1.POST("/generate", document.GenerateDocumentHandler)
	apiV1.POST("/generateForm", document.GenerateDocumentFormHandler)

	// AI文档生成服务（公开接口，不需要JWT）
	apiV1.POST("/gendoc", gendoc.GenerateDocHandler)
	apiV1.POST("/gendocForm", gendoc.GenerateDocFormHandler)

	// 健康检查（公开接口）
	r.GET("/health", document.HealthHandler)

	// 任务路由注册
	task.RegisterRoutes(apiV1)
	dashboard.RegisterRoutes(apiV1)
	meeting.RegisterRoutes(apiV1)
	lnk.RegisterRoutes(apiV1)
	user.RegisterRoutes(apiV1)
	incoming.RegisterRoutes(apiV1)

	apiV1.POST("/share/file", sharefile.ShareFileHandler)

	// 文档总结服务
	summaryService := summary.NewSummaryService()
	summaryService.RegisterRoutes(apiV1)

	err = r.Run(":8080")
	if err != nil {
		panic("gin启动失败：" + err.Error())
	}
}

// 初始化时区配置
func initTimeZone() {
	// 从环境变量获取时区，默认为上海
	tz := os.Getenv("TZ")
	if tz == "" {
		tz = "Asia/Shanghai"
	}

	loc, err := time.LoadLocation(tz)
	if err != nil {
		fmt.Printf("警告: 无法加载时区 %s, 使用 UTC+8\n", tz)
		loc = time.FixedZone("CST", 8*60*60)
	}

	time.Local = loc
	fmt.Printf("时区设置为: %s\n", tz)
}
